package com.woniuxy.controller;

import com.woniuxy.entity.User;
import com.woniuxy.entity.utils.ResponseEntity;
import com.woniuxy.jwt.JWTUtils;
import com.woniuxy.seservice.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    AuthService authService;

    @Resource
    RedisTemplate redisTemplate;


    @GetMapping("/login")
    public ResponseEntity login( User user){
        User dbuser = authService.findUser(user);
        //比较登录的是否密码和数据库密码是否一致，我们暂时不用密码加密
        if(Objects.nonNull(dbuser)&& dbuser.getPassword().equals(user.getPassword())){
            //说明登录成功
            String token = JWTUtils.generateToken(user.getUsername());
            //正常这里就需要存储到redis中！！！还要开发一个刷新token！
            ResponseEntity success = new ResponseEntity(user.getUsername());

            success.put("token",token);
            //刷新token refreshToken
            String refreshToken = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(refreshToken,dbuser);
            //刷新token60min过期
            redisTemplate.expire(refreshToken,60, TimeUnit.MINUTES);
            success.put("refreshToken",refreshToken);
            return success;
        }else {
            return ResponseEntity.ERROR;
        }
    }

}
